package xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

/**
 * 使用dom4j解析books.xml文档，将book节点封装成Book对象，将Book对象添加到ArrayList<E>集合
 * @author shkstart
 * @creat 2022-05-21:11
 */
public class BooksHandler {
    public static void main(String[] args) {
        //创建SAXReader对象
        SAXReader reader = new SAXReader();
        try {
            //读取指定路径下的xml文件，获得Document对象
            Document document = reader.read(new FileInputStream("D:\\workspace\\IDEA\\Java78\\Homework\\data\\books.xml"));
            //获取根元素
            Element rootElement = document.getRootElement();
            //获取根元素下的所有元素
            List<Element> elementList = rootElement.elements("book");
            //定义一个集合存放所有的Book对象
            List<Book> bookList = new ArrayList<>();
            //声明Book对象
            Book book = null;
            //遍历elementList集合的所有元素对象
            for(Element element:elementList){
                //获取属性的值
                String type = element.attributeValue("type");
                //下面是获取元素的值
                String title = element.elementTextTrim("title");
                String author = element.elementTextTrim("author");
                String year = element.elementTextTrim("year");
                String price = element.elementTextTrim("price");
                //创建Book对象
                book = new Book();
                //把属性值和元素值通过setXXX()方法，赋值给具体的Book对象
                book.setType(type);
                book.setTitle(title);
                book.setAuthor(author);
                book.setYear(Integer.parseInt(year));
                book.setPrice(Double.parseDouble(price));
                //将Book对象添加到booklist集合中
                bookList.add(book);

            }
            //遍历booklist集合
            for(Book book1:bookList){
                System.out.println(book1);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}
